import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useLocation } from 'react-router-dom';

/**
 * 组件权限控制
 * @param {React.Component|React.FunctionComponent} Component 需要控制的组件
 * @param {string} permission 需要的权限
 * @example
 * import { Button } from 'antd';
 * const Button2 = withPermission(Button, 'test');
 * <Button2 />
 * @returns {React.FunctionComponent}
 */
function withPermission(Component, permission) {
    return function WithPermissionComponent({ ...props }) {
        const [isValidated, setIsValidated] = useState(false);
        const userInfo = useSelector((state) => state.userInfo);
        const location = useLocation();

        useEffect(() => {
            const buttonList = [];
            const find = (list, path) => {
                return list.some((item) => {
                    if (item.address === path) {
                        buttonList.push(...item.sysMenuButtonList);
                        return true;
                    }
                    if (Array.isArray(item.children)) {
                        return find(item.children, path);
                    }
                    return false;
                });
            };
            find(userInfo.menuList, location.pathname);
            setIsValidated(buttonList.map((item) => item.buttonCode).indexOf(permission) > -1);
        }, [userInfo, location]);

        return isValidated ? <Component {...props} /> : null;
    };
}

export default withPermission;
